package cn.yeziji.forum.config;

import cn.yeziji.forum.filter.TokenRefreshFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * Web Mvc 配置
 *
 * @author gzkemays
 * @since 2021/12/22 14:02
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
  @Override
  protected void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new TokenRefreshFilter());
  }

  @Override
  protected void addCorsMappings(CorsRegistry registry) {
    registry
        // 设置允许跨域的路由
        .addMapping("/**")
        // 是否允许证书（cookies）
        .allowCredentials(true)
        // 设置允许的请求头
        .allowedHeaders("*")
        // 设置允许的方法
        .allowedMethods("*")
        // 设置允许跨域请求的域名
        .allowedOriginPatterns("*");
  }

  @Override
  protected void configurePathMatch(PathMatchConfigurer configurer) {
    String severPrefix = "/forum";
    configurer
        .addPathPrefix(severPrefix, config -> config.isAnnotationPresent(Controller.class))
        .addPathPrefix(severPrefix, config -> {
          RequestMapping annotation = config.getAnnotation(RequestMapping.class);
          String[] values = annotation.value();
          for (String value : values) {
            if (StringUtils.isNotBlank(value) && "pay".equals(value) || "/pay".equals(value)) {
              return false;
            }
          }
          return config.isAnnotationPresent(RestController.class);
        });
    //    super.configurePathMatch(configurer);
  }
}
